// 判断数据类型的功能函数
import { DataTypeOf } from '../dataTypeOf';
/**
 * 判断2个对象内的全部键值对是否全部相等的功能函数
 * @author 莫若省
 * @param obj1 第一个对象
 * @param obj2 第二个对象
 * @returns 结果true/false
 */
export const compareObjects = (obj1: any, obj2: any): boolean => {
  if (typeof obj1 !== 'object' || typeof obj2 !== 'object') {
    return false;
  }

  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);

  if (keys1.length !== keys2.length) {
    return false;
  }

  for (const key of keys1) {
    const value1 = obj1[key];
    const value2 = obj2[key];

    if (typeof value1 !== typeof value2) {
      return false;
    }

    if (typeof value1 === 'object' && typeof value2 === 'object') {
      const type1 = DataTypeOf(value1);
      const type2 = DataTypeOf(value2);

      if (type1 !== type2) {
        return false;
      }

      if (type1 === 'array') {
        if (!compareArrays(value1, value2)) {
          return false;
        }
      } else if (type1 === 'object') {
        if (!compareObjects(value1, value2)) {
          return false;
        }
      }
    } else if (value1 !== value2) {
      return false;
    }
  }

  return true;
};

const compareArrays = (arr1: any[], arr2: any[]): boolean => {
  if (arr1.length !== arr2.length) {
    return false;
  }

  for (let i = 0; i < arr1.length; i++) {
    const value1 = arr1[i];
    const value2 = arr2[i];

    if (typeof value1 !== typeof value2) {
      return false;
    }

    if (typeof value1 === 'object' && typeof value2 === 'object') {
      const type1 = DataTypeOf(value1);
      const type2 = DataTypeOf(value2);

      if (type1 !== type2) {
        return false;
      }

      if (type1 === 'array') {
        if (!compareArrays(value1, value2)) {
          return false;
        }
      } else if (type1 === 'object') {
        if (!compareObjects(value1, value2)) {
          return false;
        }
      }
    } else if (value1 !== value2) {
      return false;
    }
  }

  return true;
};
